package com.imooc.web.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Date;

/**
 * Author:   yangdc
 * Date:     2018/9/3 2:01
 */
// 使过滤器起作用有如下3种方式(暂时只总结到这么多)
// 方式一：加此注解就相当于将该过滤器加入到过滤器链
// @Component
// 方式二：使用@WebFilter和@ServletComponentScan
@WebFilter(urlPatterns = "/user/*")
// 方式三：创建WebConfig配置类(加@Configuration注解且继承WebMvcConfigurerAdapter)
public class TimeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("time filter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("===time filter start");
        long start = new Date().getTime();
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("===time filter耗时: " + (new Date().getTime() - start));
        System.out.println("===time filter finish");
    }

    @Override
    public void destroy() {
        System.out.println("time filter destroy");
    }
}
